<template>
  <div class="checkout-container">
    <Header />
    <div class="checkout-content">
      <h2 class="checkout-title">确认订单</h2>

      <!-- 课程信息 -->
      <div class="course-info">
        <div class="course-item" v-for="course in courseList" :key="course.id">
          <img :src="course.image" :alt="course.name" class="course-image">
          <div class="course-detail">
            <h3>{{ course.name }}</h3>
            <p class="validity">有效期：{{ course.validity }}</p>
          </div>
          <div class="course-price">¥{{ course.price }}</div>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="payment-method">
        <h3>支付方式</h3>
        <div class="payment-options">
          <label class="payment-option">
            <input type="radio" v-model="paymentMethod" value="alipay">
            <img src="../assets/alipay.png" alt="支付宝" class="payment-icon">
            <span>支付宝</span>
          </label>
          <label class="payment-option">
            <input type="radio" v-model="paymentMethod" value="wechat">
            <img src="../assets/weixin2.png" alt="微信支付" class="payment-icon">
            <span>微信支付</span>
          </label>
        </div>
      </div>

      <!-- 优惠券 -->
      <div class="coupon-section">
        <h3>优惠券</h3>
        <select v-model="selectedCoupon" class="coupon-select">
          <option value="">不使用优惠券</option>
          <option v-for="coupon in coupons" :key="coupon.id" :value="coupon.id">
            {{ coupon.name }}
          </option>
        </select>
      </div>

      <!-- 价格信息 -->
      <div class="price-summary">
        <div class="price-item">
          <span>商品总额</span>
          <span class="amount">¥{{ totalPrice  }}</span>
        </div>
        <div class="price-item">
          <span>优惠券</span>
          <span class="discount">-¥{{ couponAmount }}</span>
        </div>
        <div class="price-item total">
          <span>实付金额</span>
          <span class="final-price">¥{{ totalPrice  }}</span>
        </div>
      </div>

      <!-- 服务协议 -->
      <div class="agreement">
        <label>
          <input type="checkbox" v-model="agreementChecked">
          <span>我已阅读并同意</span>
          <a href="#" class="agreement-link">《服务协议》</a>
        </label>
      </div>

      <!-- 支付按钮 -->
      <div class="checkout-action">
        <button
            class="pay-button"
            :disabled="!agreementChecked || !paymentMethod"
            @click="handlePayment"
        >
          立即支付
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from 'vue'
import Header from '../components/Header.vue'
import {useRouter, useRoute} from "vue-router";
import {ElMessage} from "element-plus";
import axios from "axios";

const router = useRouter()
const route = useRoute()

const totalPrice=ref(0)

const courseList = ref([])

// 课程信息
const course = ref({
  name: 'Python全栈开发工程师',
  image: 'https://img30.360buyimg.com/jdcms/s480x480_jfs/t1/305399/38/704/166022/68201216Ff6510ba5/919edbaa90b03b77.jpg.avif',
  validity: '永久有效',
  price: 2999.00
})

// 支付方式
const paymentMethod = ref('alipay')

// 优惠券
const coupons = ref([])
const selectedCoupon = ref('')
const couponAmount = ref(0)

// 最终价格
const finalPrice = computed(() => {
  return (course.value.price - couponAmount.value).toFixed(2)
})

// 服务协议
const agreementChecked = ref(false)

// 处理支付
const handlePayment = () => {
  if (!agreementChecked.value) {
    ElMessage.warning('请先同意服务协议')
    return
  }
  if (!paymentMethod.value) {
    ElMessage.warning('请选择支付方式')
    return
  }
  // TODO: 实现支付逻辑
}

const refreshToken = async () => {
  try {
    const refreshToken = localStorage.getItem('refresh_token') || sessionStorage.getItem('refresh_token')
    if (!refreshToken) {
      throw new Error('No refresh token')
    }

    const response = await axios.post('http://127.0.0.1:8000/refresh/', {
      refresh: refreshToken
    })

    if (response.data.access) {
      // 更新access token
      const newToken = response.data.access
      localStorage.setItem('token', newToken)
      sessionStorage.setItem('token', newToken)
      return newToken
    }
    throw new Error('Failed to refresh token')
  } catch (error) {
    console.error('刷新token失败:', error)
    throw error
  }
}


const fetchCartData = async (token) => {
  try {
    const res = await axios.get("http://127.0.0.1:8000/api/carts_list/", {
      headers: {
        "Authorization": "Bearer " + token
      }
    })

    if (res.status === 200 && res.data.code === 1) {
      const coursesP = route.query.courses
      console.log(coursesP)

      const selectedCourseInfo = JSON.parse(coursesP)
      console.log(selectedCourseInfo)


      const selectedCartInfo = res.data.data.cart_list.filter(item => item.is_selected === 1)
      console.log(selectedCartInfo)

      selectedCartInfo.map(item => {
        const courseInfo = selectedCourseInfo.find(info => info.courseId === item.id)
        const mydata = {}
        mydata.id = item.id
        mydata.name = item.name
        mydata.validity = courseInfo.validityText
        mydata.price = courseInfo.price
        mydata.image = item.course_img
        courseList.value.push(mydata)

      })


      totalPrice.value = courseList.value.reduce((sum,course)=>sum+course.price,0).toFixed(2)
    } else {
      ElMessage.error(res.data.message || '获取数据失败')
    }

  } catch (error) {
    if (error.response.status === 401) {
      try {

        const newToken = await refreshToken()

        return await fetchCartData(newToken)

      } catch (error) {
        ElMessage.error('登录已过期，请重新登录')
        localStorage.removeItem('token')
        localStorage.removeItem('refresh_token')
        sessionStorage.removeItem('token')
        sessionStorage.removeItem('refresh_token')


        await router.push('/login')
      }
    } else {
      ElMessage.error('网络错误')
    }

  }

}


const initCheckOut = async () => {
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    await router.push('/login')
    return
  }

  await fetchCartData(token)

}

onMounted(() => {

  initCheckOut()

})
</script>

<style scoped>
.checkout-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.checkout-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.checkout-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
}

.course-info {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.course-item {
  display: flex;
  align-items: center;
  gap: 20px;
}

.course-image {
  width: 120px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.course-detail h3 {
  margin: 0 0 10px;
  font-size: 16px;
  color: #333;
}

.validity {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.course-price {
  margin-left: auto;
  color: #ff6b00;
  font-size: 18px;
  font-weight: bold;
}

.payment-method {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.payment-method h3 {
  margin: 0 0 15px;
  font-size: 16px;
  color: #333;
}

.payment-options {
  display: flex;
  gap: 20px;
}

.payment-option {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  cursor: pointer;
}

.payment-option:hover {
  border-color: #ff6b00;
}

.payment-icon {
  width: 24px;
  height: 24px;
}

.coupon-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.coupon-section h3 {
  margin: 0 0 15px;
  font-size: 16px;
  color: #333;
}

.coupon-select {
  width: 100%;
  padding: 10px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  font-size: 14px;
}

.price-summary {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #666;
}

.price-item.total {
  border-top: 1px solid #e8e8e8;
  padding-top: 10px;
  margin-top: 10px;
  color: #333;
}

.amount {
  color: #333;
}

.discount {
  color: #52c41a;
}

.final-price {
  color: #ff6b00;
  font-size: 20px;
  font-weight: bold;
}

.agreement {
  text-align: center;
  margin-bottom: 20px;
}

.agreement-link {
  color: #1890ff;
  text-decoration: none;
}

.agreement-link:hover {
  text-decoration: underline;
}

.checkout-action {
  text-align: center;
}

.pay-button {
  padding: 12px 40px;
  font-size: 16px;
  color: #fff;
  background: #ff6b00;
  border: none;
  border-radius: 24px;
  cursor: pointer;
  transition: all 0.3s;
}

.pay-button:hover {
  background: #ff7b00;
}

.pay-button:disabled {
  background: #ccc;
  cursor: not-allowed;
}
</style>
